package com.whros.helloworld;

import com.whros.helloword.plugin.HelloPlugin;
import com.whros.helloword.plugin.PluginInfo;
import com.whros.helloword.plugin.PluginProperties;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author whroid
 * @since 2021-07-25
 */
public class PluginLoader {

    public static List<PluginInfo> loadPlugin(String  jarPath) throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        System.out.println("plugin jarPath="+jarPath);
        File file = new File(jarPath);
        URL url = file.toURI().toURL();
        ClassLoader loader = new URLClassLoader(new URL[] { url });
        PluginProperties pluginProperties = parsePluginProperties(loader);

        if(CollectionUtils.isEmpty(pluginProperties.getPluginNames())){
            return null;
        }
        List<PluginInfo> pluginInfos = new ArrayList<>();
        for(String className: pluginProperties.getPluginNames()){
            Class<?> cls = loader.loadClass(className);
            HelloPlugin plugin = (HelloPlugin) cls.newInstance();
            System.out.println("plugin:"+plugin.getPluginName() +" version="+plugin.getPluginVersion());
            plugin.print(LocalDateTime.now().toString());
            PluginInfo pluginInfo = new PluginInfo();
            pluginInfo.setPluginName(plugin.getPluginName());
            pluginInfo.setPluginVersion(plugin.getPluginVersion());
            pluginInfo.setClassLoader(loader);
            pluginInfo.setPlugin(plugin);
            pluginInfos.add(pluginInfo);
        }
        return pluginInfos;

    }

    public static PluginProperties parsePluginProperties(ClassLoader loader){
        PluginProperties pluginProperties = new PluginProperties();
        InputStream inputStream = loader.getResourceAsStream("plugin.properties");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String value = null;
        do {

            try {
                value = bufferedReader.readLine();

                if(StringUtils.isBlank(value)){
                    break;
                }
                String[] strs = value.split("=");
                if(StringUtils.equals(strs[0], "hello.plugin")){
                    List<String> plugin = Arrays.stream(strs[1].split(",")).filter(StringUtils::isNotBlank).collect(Collectors.toList());
                    pluginProperties.setPluginNames(plugin);
                }
            } catch (IOException e) {
                break;
            }
            System.out.println(value);
        }while (true);
        return pluginProperties;
    }
}
